﻿Imports System.Net
Imports System.IO

Module put

    Dim sito As String
    Dim password As String
    Dim user As String
    Dim filein As String
    Dim fileout As String
    Dim passout As Integer = 0 'se deve creare il file .OK con le informazioni di upload

    Sub Main()

        Dim s() As String = System.Environment.GetCommandLineArgs()

        Try
            sito = s(1)
            user = s(2)
            password = s(3)
            filein = s(4)
            fileout = s(5)
        Catch ex As Exception
            Console.WriteLine("ftpput.exe sitename username password filein fileout")
            Console.WriteLine("ftpput www.mysite.com myuser mypassword c:\test.xxx /mydir/test.xxx")
            End
        End Try

        Try
            passout = s(6)
        Catch ex As Exception
            passout = 0
        End Try

        Dim risp As Int64 = 0

        risp = sendfile2()

        If risp <> -1 Then
            For conta_reconnect = 0 To 3
                Console.WriteLine("Reconnect nr.:" & conta_reconnect)
                System.Threading.Thread.Sleep(10000)
                risp = sendfile2(risp)
                If risp = -1 Then
                    Exit For
                End If
            Next

        End If


    End Sub


    Public Function sendfile2(Optional startfrom As Int64 = 0) As Int64

        Const bufferLength As Integer = 1024 * 100
        Dim buffer As Byte() = New Byte(bufferLength - 1) {}
        Dim count As Integer = startfrom
        Dim readBytes As Integer = 0
        Dim stream As FileStream = File.OpenRead(filein)
        Dim nrloop As Integer = 0

        If startfrom > 0 Then
            Dim ctl As Integer = startfrom / 1024 / 100
            For i = 0 To ctl
                readBytes = stream.Read(buffer, 0, bufferLength)
            Next
        End If

        Do
            readBytes = stream.Read(buffer, 0, bufferLength)
            Try
                Dim request As FtpWebRequest = DirectCast(WebRequest.Create("ftp://" & sito & fileout), FtpWebRequest)
                request.UsePassive = False
                request.KeepAlive = False
                request.Credentials = New NetworkCredential(user, password)
                If nrloop > 0 Then
                    request.Method = WebRequestMethods.Ftp.AppendFile
                Else
                    If startfrom = 0 Then
                        request.Method = WebRequestMethods.Ftp.UploadFile
                    Else
                        request.Method = WebRequestMethods.Ftp.AppendFile
                    End If
                End If

                Dim requestStream As Stream = request.GetRequestStream()
                requestStream.Write(buffer, 0, readBytes)
                requestStream.Flush()
                requestStream.Close()
                Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
                response.Close()
                count += readBytes
                nrloop = nrloop + 1
                Console.Write(".")
            Catch ex As Exception
                Console.WriteLine("ERROR BUFFER:" & ex.Message)
                Return count
                Exit Do
            End Try

            If nrloop Mod 10 = 0 Then
                Console.WriteLine(nrloop * 1024 * 100 & " Byte Transfert")
            End If
        Loop While readBytes <> 0

        Try

            'get an error here. Also dont think I can avoid this statement
            'Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
            'response.Close()
            Console.WriteLine("OK Transfert file:" & filein & " to:" & fileout)
            Return -1
        Catch ex As Exception
            Console.WriteLine("ERROR GENERAL:" & ex.Message)
            Return count
        End Try

    End Function

    Public Sub ResumeFtpFileDownload(sourceUri As Uri, destinationFile As String)
        Dim file As New FileInfo(destinationFile)
        Dim localfileStream As FileStream
        Dim request As FtpWebRequest = TryCast(WebRequest.Create(sourceUri), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.DownloadFile
        If file.Exists Then
            request.ContentOffset = file.Length
            localfileStream = New FileStream(destinationFile, FileMode.Append, FileAccess.Write)
        Else
            localfileStream = New FileStream(destinationFile, FileMode.Create, FileAccess.Write)
        End If
        Dim response As WebResponse = request.GetResponse()
        Dim responseStream As Stream = response.GetResponseStream()
        Dim buffer As Byte() = New Byte(1023) {}
        Dim bytesRead As Integer = responseStream.Read(buffer, 0, 1024)
        While bytesRead <> 0
            localfileStream.Write(buffer, 0, bytesRead)
            bytesRead = responseStream.Read(buffer, 0, 1024)
        End While
        localfileStream.Close()
        responseStream.Close()
    End Sub









    'Private Function SendToFtp(resend__1 As Integer, filename As String, ftpServerIP As String, userName As String, Password As String) As privatevoid
    '    Try



    '        Dim tempFileSize As Long = 0


    '        Dim fileInf As New FileInfo(filename)



    '        Dim uri As String = (Convert.ToString("ftp://") & ftpServerIP) + "/" + fileInf.Name
    '        Dim reqFTP As FtpWebRequest





    '        reqFTP = DirectCast(FtpWebRequest.Create(New Uri((Convert.ToString("ftp://") & ftpServerIP) + "/" + fileInf.Name)), FtpWebRequest)



    '        reqFTP.Credentials = New NetworkCredential(userName, Password)



    '        reqFTP.KeepAlive = False




    '        If resend__1 = Resend Then
    '            reqFTP.Method = WebRequestMethods.Ftp.UploadFile
    '        Else


    '            reqFTP.Method = WebRequestMethods.Ftp.AppendFile
    '        End If
    '        tempFileSize = GetFileLengthFromFtp(filename, ftpServerIP, userName, Password)

    '        If tempFileSize > 0 AndAlso Not DeleteFromFtp(filename, ftpServerIP, userName, Password, tempFileSize) Then

    '            Return
    '        End If



    '        reqFTP.UseBinary = True


    '        reqFTP.ContentLength = fileInf.Length


    '        If passive = 1 Then

    '            reqFTP.UsePassive = True
    '        Else



    '            reqFTP.UsePassive = False
    '        End If


    '        Dim fs As FileStream = fileInf.OpenRead()
    '        Dim strm As Stream = reqFTP.GetRequestStream()
    '        Try




    '            Console.WriteLine("File Size To Be Write:" + fileInf.Length.ToString() + " bytes")


    '            Console.WriteLine("File Size allready  Wrote:" + tempFileSize.ToString() + " bytes")

    '            Dim buffLength As Integer = 1024


    '            Dim buff As Byte() = newbyte(buffLength)


    '            Dim contentLen As Integer = 0

    '            If fileInf.Length > buffLength Then
    '                buffLength = 1024
    '                contentLen = fs.Read(buff, 0, 1024)
    '            Else



    '                buffLength = CInt(fileInf.Length)
    '                contentLen = fs.Read(buff, 0, buffLength)
    '            End If


    '            Dim countt As Long = 0


    '            While contentLen <> 0
    '                strm.Write(buff, 0, buffLength)
    '                BytesSent += contentLen
    '                contentLen = fs.Read(buff, 0, buffLength)
    '                countt += contentLen
    '            End While
    '            strm.Flush()
    '            fs.Flush()
    '            strm.Close()
    '            fs.Close()
    '        Catch ex As Exception

    '            MessageBox.Show(strm.Position.ToString())
    '            strm.Flush()
    '            fs.Flush()
    '            fs.Close()
    '            reqFTP.Abort()
    '            fs.Close()

    '            FtperrorLog(ex.Message)


    '            If resend__1 > 0 Then

    '                Dim retryattemptLeft As Integer = resend__1 - 1
    '                Thread.Sleep(10000)


    '                FtperrorLog("Retrying.. to Upload (" + retryattemptLeft.ToString() + " Retry Attempts Left")
    '                SendToFtp(retryattemptLeft, filename, ftpServerIP, userName, Password)
    '            End If
    '        End Try
    '    Catch generatedExceptionName As Exception


    '        MessageBox.Show("error")
    '    End Try
    'End Function


End Module
